import { ExtractJwt, Strategy, StrategyOptions } from 'passport-jwt'
import { PassportStrategy } from '@nestjs/passport'
import { Injectable, UnauthorizedException } from '@nestjs/common'
import { AuthService } from './auth.service'
import { ConfigService } from '@nestjs/config'

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private readonly authService: AuthService,
    private readonly configService: ConfigService
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.get('JWT_SECRET', 'test123456')
    } as StrategyOptions)
  }

  async validate(payload: any) {
    // console.log('payload', payload.exp)
    // console.log('payload', payload)
    //这里接受的user 是解析token 之后拼装返回的payload
    const existUser = await this.authService.getUser(payload)
    if (!existUser) {
      throw new UnauthorizedException('token不正确')
    }
    const roleNames = existUser.roles.map((role) => ({ name: role.name, id: role.id }));
    const { roles, ...rest } = existUser
    return { ...rest, role: roleNames }
  }
}
